package org.distributed.transaction.core.interceptor;

import org.distributed.transaction.core.context.TracingContext;
import org.distributed.transaction.core.context.TransactionContext;
import org.distributed.transaction.core.executor.TransactionExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TransactionInterceptor {
	
	private static final Logger logger = LoggerFactory.getLogger(TransactionInterceptor.class);

	@Autowired
	private TransactionExecutor transactionExecutor;

	public Object doInvokeTransaction(TransactionContext transactionContext) throws Throwable {
		
		logger.info("start distributed transaction");
		/**
		 * 根据是否有事务组 判断当前是否为事务发起者
		 */
		boolean hashGroup = TracingContext.tracing().hasGroup();
		if (!hashGroup) {
			// 事务发起者
			transactionContext.setTransactionStart(!hashGroup);
			// 开启事务组
			TracingContext.tracing().beginTransactionGroup();
			// 设置事务组id
			transactionContext.setGroupId(TracingContext.tracing().groupId());
		}
		try {
			return transactionExecutor.execute(transactionContext);
		} finally {
			
		}
		
	}
}
